package com.song.designmodel.strategyPattern;

import com.song.designmodel.strategyPattern.service.CustomerService;
import com.song.designmodel.strategyPattern.service.DefaultCustomerService;
import jakarta.annotation.Nonnull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

@RestController
public class CustomerController {

    private Map<UserType, CustomerService> customerServiceMap;

    @Autowired
    private DefaultCustomerService defaultCustomerService;

    @GetMapping("/customer/{recharge}")
    public String customer(@PathVariable(value = "recharge") int recharge) {
        UserType userType = UserType.typeOf(recharge);
        CustomerService customerService = customerServiceMap.getOrDefault(userType, defaultCustomerService);
        return customerService.findCustomer();
    }

    @Autowired
    public void getCustomerServiceList(List<CustomerService> customerServiceList) {
        this.customerServiceMap =
                customerServiceList.stream()
                        .filter(customerService -> customerService.getClass().isAnnotationPresent(SupportUserType.class))
                        .collect(Collectors.toMap(this::findUserTypeFromService, Function.identity()));
        if (this.customerServiceMap.size() != UserType.values().length) {
            throw new IllegalArgumentException("有用户类型没有对应的策略");
        }
    }

    private UserType findUserTypeFromService(@Nonnull CustomerService customerService) {
        SupportUserType annotation = customerService.getClass().getAnnotation(SupportUserType.class);
        return annotation.value();
    }

}
